<script setup lang="ts">
import { ref } from 'vue'
import type { LoginParams } from '../../types/user'
import { loginApi } from '@/apis/user'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref()
const formModel = ref<LoginParams>({
  mobile: '13200000000',
  code: '246810',
  isAgree: true,
})
const rules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      validator: (rule: unknown, value: string, callback: (err?: Error) => void) => {
        // 对value进行校验，此时的value就是form.mobile
        if (/^1[3-9]\d{9}$/.test(value)) {
          // 通过
          callback()
        } else {
          callback(new Error('手机号格式不对'))
        }
      },
      trigger: 'blur',
    },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码是6个字符', trigger: 'blur' },
  ],
  isAgree: [
    { required: true, message: '请同意用户协议和隐私条款', trigger: 'blur' },
    {
      validator: (rule: unknown, value: boolean, callback: (err?: Error) => void) => {
        if (value) {
          callback()
        } else {
          callback(new Error('请同意用户协议和隐私条款'))
        }
      },
      trigger: 'blur',
    },
  ],
}
const login = async () => {
  await formRef.value.validate()
  formModel.value.isAgree = undefined
  const res = await loginApi(formModel.value)
  userStore.setToken(res.token)
  router.replace('/')
}
</script>

<template>
  <div class="container">
    <!-- 白色卡片 -->
    <el-card>
      <!-- logo -->
      <img class="logo" src="../../assets/logo.png" alt="" />
      <!-- 表单 -->
      <el-form ref="formRef" status-icon :model="formModel" :rules="rules">
        <el-form-item prop="mobile">
          <el-input v-model="formModel.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="formModel.code" placeholder="请输入验证码"></el-input>
        </el-form-item>
        <el-form-item prop="isAgree">
          <el-checkbox v-model="formModel.isAgree"
            >我已阅读并同意「用户协议」和「隐私条款」</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login()">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="less">
.container {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(../../assets/login.png) no-repeat center / cover;
  // 饿了么的组件解析后，组件根标签回加载一个和组件名称一致的类名
  .el-card {
    width: 440px;
    height: 360px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
    .el-form {
      padding: 0 20px;
      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
